import React, { useEffect, useState } from 'react';
import { Button, Card, List, Space, Tag, Typography, Popconfirm, message } from 'antd';
import { EditOutlined, DeleteOutlined, RocketOutlined, ExperimentOutlined, PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Agent, getAllAgents, deleteAgent } from '@/api/agent';
import './style.less';

const { Title, Text } = Typography;

const AgentList: React.FC = () => {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const navigate = useNavigate();

  const fetchAgents = async () => {
    try {
      setLoading(true);
      const data = await getAllAgents();
      setAgents(data);
    } catch (error) {
      message.error('获取智能体列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAgents();
  }, []);

  const handleDelete = async (id: number) => {
    try {
      await deleteAgent(id);
      message.success('删除成功');
      fetchAgents();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const getStatusTag = (status?: string) => {
    if (!status) return null;
    const statusMap = {
      active: { color: 'green', text: '活跃' },
      training: { color: 'blue', text: '训练中' },
      inactive: { color: 'default', text: '未激活' },
    };
    const config = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const formatTime = (time?: string) => {
    if (!time) return '-';
    return new Date(time).toLocaleString('zh-CN');
  };

  return (
    <div className="agent-list-container">
      <div className="agent-list-header">
        <Title level={2}>智能体列表</Title>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={() => navigate('/agent/create')}
        >
          创建智能体
        </Button>
      </div>
      
      <List
        grid={{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }}
        dataSource={agents}
        loading={loading}
        renderItem={(agent) => (
          <List.Item>
            <Card 
              className="agent-card"
              title={
                <div className="agent-card-title">
                  <span>{agent.name}</span>
                  {getStatusTag(agent.status)}
                </div>
              }
              actions={[
                <Button 
                  key="use" 
                  type="text" 
                  icon={<RocketOutlined />}
                  onClick={() => navigate(`/chat/agent/${agent.id}`)}
                >
                  使用
                </Button>,
                <Button 
                  key="train" 
                  type="text" 
                  icon={<ExperimentOutlined />}
                  disabled={!agent.trainable}
                  onClick={() => navigate(`/agent/train/${agent.id}`)}
                >
                  训练
                </Button>,
                <Button 
                  key="edit" 
                  type="text" 
                  icon={<EditOutlined />}
                  onClick={() => navigate(`/agent/edit/${agent.id}`)}
                >
                  编辑
                </Button>,
                <Popconfirm
                  key="delete"
                  title="确定要删除这个智能体吗？"
                  onConfirm={() => agent.id && handleDelete(agent.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button 
                    type="text" 
                    danger 
                    icon={<DeleteOutlined />}
                  >
                    删除
                  </Button>
                </Popconfirm>
              ]}
            >
              <div className="agent-card-content">
                <div className="agent-info-item">
                  <Text type="secondary">版本：</Text>
                  <Text>{agent.version || 1}</Text>
                </div>
                <div className="agent-info-item">
                  <Text type="secondary">可训练：</Text>
                  <Text>{agent.trainable ? '是' : '否'}</Text>
                </div>
                <div className="agent-info-item">
                  <Text type="secondary">更新时间：</Text>
                  <Text>{formatTime(agent.updateTime)}</Text>
                </div>
              </div>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};

export default AgentList; 